package com.project8.main;

import java.io.File;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;


public class BookList extends ListActivity { 
	
	ArrayList<String> bookList = new ArrayList<String>();
	ArrayList<String> bookDescriptions = new ArrayList<String>();
	ArrayList<Bitmap> bookImages = new ArrayList<Bitmap>();
	ArrayList<String> authors = new ArrayList<String>();
	
	//Internal Storage
	private static final String internalStorage= Environment.getExternalStorageDirectory() + "/Textbooks/";
	
	String[] bookArray = null;
	Context appContext;
	
	String[] fileNames = null;
	File booksInDirectory = new File(internalStorage);
	
	private int position;
	private IconicAdapter I; 

	@SuppressWarnings("unchecked")
	@Override
	public void onCreate(Bundle savedInstanceState) {
	  super.onCreate(savedInstanceState);
	  
	  appContext = this;
	  	
	  Bundle bun = getIntent().getExtras();
	  bookList = (ArrayList<String>) bun.get("BookList");
	  bookImages = (ArrayList<Bitmap>) bun.get("BookImages");
	  bookDescriptions = (ArrayList<String>) bun.get("BookDescriptions");
	  authors = getAuthors(bookDescriptions);
	  
	  bookArray = (String[]) bookList.toArray(new String[0]);

	  I = new IconicAdapter();
	  
	  setListAdapter(I);
	  
	  ListView lv = getListView();
	  lv.setTextFilterEnabled(true);
	  lv.setBackgroundColor(Color.WHITE);
	  lv.setCacheColorHint(Color.WHITE);
	  
	  fileNames = booksInDirectory.list(); 
	  
	  lv.setOnItemClickListener(new OnItemClickListener() {
	   

		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			 
			 setPosition(position);
			 
			 Builder builder = new AlertDialog.Builder(appContext);
			 
             builder.setTitle(bookArray[position]);
             
             Drawable d = new BitmapDrawable(bookImages.get(position));

             builder.setIcon(d);           
             
             builder.setMessage(bookDescriptions.get(position));
             
             builder.setPositiveButton("Download", new OnClickListener(){
            		
	  				public void onClick(DialogInterface dialog, int which) {
	  					new BookDownloader(showDialog(), bookArray[getPosition()], appContext).execute();
	  				}
	              	 
	               });
             
             
             for(int i = 0; i < fileNames.length; i++)
             {	  
		    	  if(fileNames[i].equals(bookArray[position]))
		    	  {
		    		  builder.setPositiveButton("Delete", new OnClickListener(){
		            		
			  				public void onClick(DialogInterface dialog, int which) {
			  					File deleteDirectory = new File(internalStorage + bookArray[getPosition()]);
					    		  
					    		deleteDir(deleteDirectory);
					    		
					    		for(int b = 0; b < Global.books.size(); b++)
					    		{
					    			if(Global.books.get(b).getBookTitle().equals(bookArray[getPosition()]))
					    			{
					    				Global.books.remove(b);
					    			}
					    		}
					    		
					    		updateAdapter();
			  				}
			              	 
			               });
		    	  }
             }
			   
         

             builder.setNegativeButton("Cancel", null);

             builder.show();
             
             
			
    		 
		}
	  });
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		updateAdapter();
	}
	
	public void updateAdapter()
	{
		I.notifyDataSetChanged();
	}
	public ProgressDialog showDialog()
	{
		ProgressDialog dialog = ProgressDialog.show(this, "", 
                "Downloading Book", true);
		
		return dialog;
	}

	class IconicAdapter extends ArrayAdapter<String> {
	    IconicAdapter() {
	      super(BookList.this, R.layout.books, R.id.bookTitle, bookArray);
	    }   
	    
		public View getView(int position, View convertView,
		                       ViewGroup parent) {
			
				
		      View row = super.getView(position, convertView, parent);
		     
		      ImageView icon = (ImageView)row.findViewById(R.id.icon);
		      ImageView listThumb = (ImageView)row.findViewById(R.id.listThumb);
		      TextView  author = (TextView)row.findViewById(R.id.bookAuthor);
		      
		      Drawable d = new BitmapDrawable(bookImages.get(position));
		      
		      icon.setImageResource(R.drawable.blank);
		      listThumb.setImageDrawable(d);
		      author.setText("Author:" + authors.get(position));
		      
		      fileNames = booksInDirectory.list();
		      		      		      
		      for(int i = 0; i < fileNames.length; i++)
			  {	  
		    	  System.out.println(fileNames[i]);
		    	  
		    	  if(fileNames[i].equals(bookArray[position]))
		    	  {
		    		 icon.setImageResource(R.drawable.accept);
		    	  }      	  
			  
			  }

		      
		      		      
		      return(row);
		}    
	
	}
	
	public int getPosition() {
		return position;
	}

	public void setPosition(int position) {
		this.position = position;
	}
	
	// Deletes all files and subdirectories under dir.
	// Returns true if all deletions were successful.
	// If a deletion fails, the method stops attempting to delete and returns false.
	public boolean deleteDir(File dir) {
	    if (dir.isDirectory()) {
	        String[] children = dir.list();
	        for (int i=0; i<children.length; i++) {
	            boolean success = deleteDir(new File(dir, children[i]));
	            if (!success) {
	                return false;
	            }
	        }
	    }
	
	    // The directory is now empty so delete it
	    return dir.delete();
	}
	
	public ArrayList<String> getAuthors(ArrayList<String> descriptions)
	{
		ArrayList<String> returnAuthors = new ArrayList<String>();
		
		for(int i = 0; i < descriptions.size(); i++)
		{
			String temp = descriptions.get(i);
			
		    returnAuthors.add(temp.substring(temp.indexOf(":") + 1, temp.indexOf("Description:")));
		}
		
		return returnAuthors;
	}

	
}//End Class


